python count nested keys

36

python count nested keys -

# Example usage:
# If you want to count keys in a nested dictionary, you can use this
# recursive function:

def count_keys(d):
    """
    recursively count keys in a nested dictionary
    """
    keys = 0
    if type(d) == dict:
        for key in d.keys():
            if isinstance(d[key], dict):
                keys += 1
                k = count_keys(d[key])
                keys += k
            else:
                keys += 1
    return keys

Comments

Submit
0 Comments